import { apiClient } from './apiClient';
import type { 
  Permission, 
  PaginatedResponse, 
  CreatePermissionRequest,
  UpdatePermissionRequest 
} from '@/types';

export interface GetPermissionsParams {
  page?: number;
  pageSize?: number;
  search?: string;
  module?: string;
  status?: 'active' | 'inactive';
}

export interface PermissionBatchOperationParams {
  ids: string[];
  operation: 'delete' | 'activate' | 'deactivate';
}

class PermissionService {
  private baseUrl = '/api/permissions';

  /**
   * 获取权限列表
   */
  async getPermissions(params: GetPermissionsParams): Promise<Permission[]> {
    const { data } = await apiClient.get<PaginatedResponse<Permission>>(this.baseUrl, {
      params
    });
    return data.items;
  }

  /**
   * 获取权限详情
   */
  async getPermissionById(id: string): Promise<Permission> {
    const { data } = await apiClient.get<Permission>(`${this.baseUrl}/${id}`);
    return data;
  }

  /**
   * 创建权限
   */
  async createPermission(permission: CreatePermissionRequest): Promise<Permission> {
    const { data } = await apiClient.post<Permission>(this.baseUrl, permission);
    return data;
  }

  /**
   * 更新权限
   */
  async updatePermission(id: string, permission: UpdatePermissionRequest): Promise<Permission> {
    const { data } = await apiClient.put<Permission>(`${this.baseUrl}/${id}`, permission);
    return data;
  }

  /**
   * 删除权限
   */
  async deletePermission(id: string): Promise<void> {
    await apiClient.delete(`${this.baseUrl}/${id}`);
  }

  /**
   * 批量删除权限
   */
  async deletePermissions(ids: string[]): Promise<void> {
    await apiClient.delete(`${this.baseUrl}/batch`, {
      data: { ids }
    });
  }

  /**
   * 批量操作权限
   */
  async batchOperation(params: PermissionBatchOperationParams): Promise<void> {
    await apiClient.post(`${this.baseUrl}/batch-operation`, params);
  }

  /**
   * 获取权限模块列表
   */
  async getPermissionModules(): Promise<string[]> {
    const { data } = await apiClient.get<string[]>(`${this.baseUrl}/modules`);
    return data;
  }

  /**
   * 获取权限代码列表（用于验证重复）
   */
  async getPermissionCodes(): Promise<string[]> {
    const { data } = await apiClient.get<string[]>(`${this.baseUrl}/codes`);
    return data;
  }

  /**
   * 验证权限代码是否可用
   */
  async validatePermissionCode(code: string, excludeId?: string): Promise<boolean> {
    const { data } = await apiClient.get<{ available: boolean }>(`${this.baseUrl}/validate-code`, {
      params: { code, excludeId }
    });
    return data.available;
  }

  /**
   * 获取权限树结构（按模块分组）
   */
  async getPermissionTree(): Promise<Record<string, Permission[]>> {
    const { data } = await apiClient.get<Record<string, Permission[]>>(`${this.baseUrl}/tree`);
    return data;
  }

  /**
   * 同步权限（从代码中自动发现权限）
   */
  async syncPermissions(): Promise<{ 
    added: Permission[]; 
    updated: Permission[]; 
    removed: Permission[] 
  }> {
    const { data } = await apiClient.post<{
      added: Permission[];
      updated: Permission[];
      removed: Permission[];
    }>(`${this.baseUrl}/sync`);
    return data;
  }

  /**
   * 导出权限配置
   */
  async exportPermissions(format: 'json' | 'csv' | 'excel' = 'json'): Promise<Blob> {
    const response = await apiClient.get(`${this.baseUrl}/export`, {
      params: { format },
      responseType: 'blob'
    });
    return response.data;
  }

  /**
   * 导入权限配置
   */
  async importPermissions(file: File): Promise<{
    success: number;
    failed: number;
    errors: string[];
  }> {
    const formData = new FormData();
    formData.append('file', file);
    
    const { data } = await apiClient.post<{
      success: number;
      failed: number;
      errors: string[];
    }>(`${this.baseUrl}/import`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    return data;
  }
}

export const permissionService = new PermissionService();